<template>
  <div class="fishing-circle-editor">
    <div class="editor-content">
      <div class="editor-header">
        <h3>{{ isEditMode ? '编辑钓点圈' : '创建钓点圈' }}</h3>
        <button class="close-btn" @click="close">×</button>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载钓点圈数据...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="loadError" class="error-container">
        <div class="error-icon">⚠️</div>
        <p>{{ loadError }}</p>
        <div class="error-actions">
          <button class="btn btn-primary" @click="retryLoad" v-if="isEditMode">重试</button>
          <button class="btn btn-secondary" @click="close">返回</button>
        </div>
      </div>

      <!-- 编辑表单 -->
      <div v-else class="editor-body">
        <div class="form-group">
          <label>钓点圈名称 <span class="required">*</span></label>
          <input 
            type="text" 
            v-model="polygonData.name" 
            placeholder="输入钓点圈名称"
            class="form-input"
            required
          />
          <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
        </div>

        <!-- 图片上传 -->
        <div class="form-group">
          <label>上传图片 <span class="required">*</span> ({{ polygonData.images.length }}/6)</label>
          <div class="images-upload">
            <input 
              type="file" 
              accept="image/*" 
              @change="handleImageUpload"
              class="file-input"
              ref="fileInput"
              multiple
            />
            <div class="upload-grid">
              <div 
                v-for="(image, index) in polygonData.images" 
                :key="index"
                class="image-item"
              >
                <img :src="image" :alt="`钓点圈图片 ${index + 1}`" class="uploaded-image"/>
                <button class="remove-image-btn" @click.stop="removeImage(index)">×</button>
              </div>
              <div 
                v-if="polygonData.images.length < 6"
                class="upload-area add-image"
                @click.stop="triggerFileUpload"
              >
                <div class="upload-placeholder">
                  <span>📷</span>
                  <span>添加图片</span>
                </div>
              </div>
            </div>
          </div>
          <span v-if="errors.images" class="error-message">{{ errors.images }}</span>
        </div>

        <!-- 坐标点列表 -->
        <div class="form-group">
          <div class="points-header" @click="togglePointsList">
            <label>坐标点列表 ({{ polygonData.points.length }}个点)</label>
            <span class="toggle-icon">{{ showPoints ? '▼' : '▶' }}</span>
          </div>
          <div v-show="showPoints" class="points-list">
            <div v-for="(point, index) in polygonData.points" :key="index" class="point-item">
              <span class="point-number">{{ index + 1 }}</span>
              <span class="point-coords">
                {{ point.lat.toFixed(6) }}, {{ point.lng.toFixed(6) }}
              </span>
            </div>
          </div>
        </div>

        <!-- 面积计算 -->
        <div class="form-group" v-if="area">
          <label>面积</label>
          <div class="area-display">{{ area }} 平方米</div>
        </div>

        <!-- 中心点 -->
        <div class="form-group" v-if="polygonData.centerPoint.lat">
          <label>中心点坐标</label>
          <div class="center-display">
            {{ polygonData.centerPoint.lat.toFixed(6) }}, {{ polygonData.centerPoint.lng.toFixed(6) }}
          </div>
        </div>

        <!-- 描述 -->
        <div class="form-group">
          <label>描述 <span class="required">*</span></label>
          <textarea 
            v-model="polygonData.description" 
            placeholder="请输入钓点圈的描述信息..."
            class="description-input"
            rows="3"
            required
          ></textarea>
          <span v-if="errors.description" class="error-message">{{ errors.description }}</span>
        </div>
      </div>

      <div class="editor-footer">
        <button class="btn btn-secondary" @click="close">取消</button>
        <button class="btn btn-primary" @click="save">{{ isEditMode ? '更新' : '保存' }}</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { useImageProcessor } from '../../../composables/useImageProcessor'

interface Point {
  lat: number
  lng: number
}

interface PolygonData {
  name: string
  images: string[]
  points: Point[]
  area: number
  description: string
  centerPoint: Point
}

const props = defineProps<{
  visible?: boolean
  points?: Point[]
  initialData?: PolygonData
  mode?: 'create' | 'edit'
  id?: string
}>()

const emit = defineEmits<{
  close: []
  save: [data: PolygonData]
}>()

// 路由相关
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

const polygonData = ref<PolygonData>({
  name: '',
  images: [],
  points: [],
  area: 0,
  description: '',
  centerPoint: { lat: 0, lng: 0 }
})

const { processImageAndCreateTempFile } = useImageProcessor()

const fileInput = ref<HTMLInputElement>()
const showPoints = ref(false)
const loading = ref(false)
const loadError = ref('')

// 表单验证错误
const errors = ref({
  name: '',
  images: '',
  description: ''
})

// 计算面积
const area = computed(() => {
  if (polygonData.value.points.length < 3) return 0
  return calculatePolygonArea(polygonData.value.points)
})

// 编辑模式判断
const isEditMode = computed(() => {
  return route.query.isUpdate === 'true' && route.params.id
})

onMounted(async () => {
  // 检查路由参数
  const routeId = route.params.id as string
  const isUpdate = route.query.isUpdate === 'true'
  
  if (isUpdate && routeId) {
    // 编辑模式 - 从API获取数据
    loading.value = true
    loadError.value = ''
    
    try {
        const response = await invoke('get_fishing_circle_detail', {
          id: routeId
        })
      
      let circleData = response as any
        
        // 检查数据结构，处理可能的嵌套
        if (circleData && circleData.data) {
          circleData = circleData.data
        }
        
        // 添加空值检查
        if (!circleData) {
          throw new Error('获取到的数据为空')
        }
        
        polygonData.value = {
          name: circleData.title || '',
          images: circleData.pics || [],
          points: Array.isArray(circleData.points) 
            ? circleData.points.map((p: any) => ({ 
                lat: p?.latitude || 0, 
                lng: p?.longitude || 0 
              }))
            : [],
          area: parseFloat(circleData.area) || 0,
          description: circleData.description || '',
          centerPoint: { 
            lat: circleData?.latitude || 0, 
            lng: circleData?.longitude || 0 
          }
        }
    } catch (error) {
      console.error('获取钓点圈详情失败:', error)
      loadError.value = '获取钓点圈详情失败，请稍后重试'
    } finally {
      loading.value = false
    }
  } else if (props.initialData) {
    // 组件模式 - 使用传入的初始数据
    polygonData.value = { ...props.initialData }
  } else {
    // 创建模式 - 使用props数据
    if (props.points) {
      polygonData.value.points = [...props.points]
      polygonData.value.area = area.value
      polygonData.value.centerPoint = calculatePolygonCenter(props.points)
    }
  }
})

function triggerFileUpload() {
  fileInput.value?.click()
}

async function handleImageUpload(event: Event) {
  const files = (event.target as HTMLInputElement).files
  if (files) {
    const remainingSlots = 6 - polygonData.value.images.length
    const filesToProcess = Array.from(files).slice(0, remainingSlots)
    
    try {
      const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}')
      const jwtToken = currentUser.token
      
      if (!jwtToken) {
        alert('请先登录')
        return
      }

      for (const file of filesToProcess) {
        try {
          // 使用通用图片处理方法
          const tempFilePath = await processImageAndCreateTempFile(file)
          
          // 上传到服务器
          const uploadedUrl = await invoke('upload_image_file', {
            filePath: tempFilePath,
            jwtToken: jwtToken
          })
          
          polygonData.value.images.push(uploadedUrl as string)
        } catch (error: any) {
          console.error('上传失败:', error)
          
          const errorMessage = error?.toString() || '未知错误'
          
          // 网络连接错误处理
          if (errorMessage.includes('10061') || errorMessage.includes('连接') || errorMessage.includes('tcp')) {
            window.showToast?.(`图片 ${file.name} 上传失败: 服务器连接失败，请检查网络或联系管理员`, 'error')
          } else if (errorMessage.includes('空响应') || errorMessage.includes('响应格式')) {
            window.showToast?.(`图片 ${file.name} 上传失败: 服务器响应异常，请稍后重试`, 'error')
          } else {
            window.showToast?.(`图片 ${file.name} 上传失败: ${errorMessage}`, 'error')
          }
        }
      }
    } catch (error: any) {
        console.error('处理图片上传时出错:', error)
        window.showToast?.(`处理图片上传时出错: ${error?.toString() || '未知错误'}`, 'error')
      }
  }
}

function removeImage(index: number) {
  const image = polygonData.value.images[index]
  if (image && image.startsWith('blob:')) {
    URL.revokeObjectURL(image)
  }
  polygonData.value.images.splice(index, 1)
}

function togglePointsList() {
  showPoints.value = !showPoints.value
}





function calculatePolygonArea(points: Point[]): number {
  if (points.length < 3) return 0
  
  let area = 0
  const n = points.length
  
  for (let i = 0; i < n; i++) {
    const j = (i + 1) % n
    area += points[i].lng * points[j].lat
    area -= points[j].lng * points[i].lat
  }
  
  area = Math.abs(area) / 2
  
  // 转换为平方米（假设1度约等于111公里）
  const metersPerDegree = 111000
  return Math.round(area * metersPerDegree * metersPerDegree)
}

function calculatePolygonCenter(points: Point[]): Point {
  if (points.length === 0) return { lat: 0, lng: 0 }
  
  let latSum = 0
  let lngSum = 0
  
  points.forEach(point => {
    latSum += point.lat
    lngSum += point.lng
  })
  
  return {
    lat: latSum / points.length,
    lng: lngSum / points.length
  }
}

function close() {
  const routeId = route.params.id as string
  const isUpdate = route.query.isUpdate === 'true'
  
  if (isUpdate && routeId) {
    // 路由模式 - 返回详情页
    router.push('/circle-detail/' + routeId)
  } else {
    // 组件模式 - 触发关闭事件
    emit('close')
  }
}

async function retryLoad() {
  if (!isEditMode.value) return
  
  const routeId = route.params.id as string
  if (!routeId) return
  
  loading.value = true
  loadError.value = ''
  
  try {
    const response = await invoke('get_fishing_circle_detail', {
      id: routeId
    })
    
    let circleData = response as any
    
    // 检查数据结构，处理可能的嵌套
    if (circleData && circleData.data) {
      circleData = circleData.data
    }
    
    // 添加空值检查
    if (!circleData) {
      throw new Error('获取到的数据为空')
    }
    
    polygonData.value = {
      name: circleData.title || '',
      images: circleData.pics || [],
      points: Array.isArray(circleData.points) 
        ? circleData.points.map((p: any) => ({ 
            lat: p?.latitude || 0, 
            lng: p?.longitude || 0 
          }))
        : [],
      area: parseFloat(circleData.area) || 0,
      description: circleData.description || '',
      centerPoint: { 
        lat: circleData?.latitude || 0, 
        lng: circleData?.longitude || 0 
      }
    }
  } catch (error) {
    console.error('获取钓点圈详情失败:', error)
    loadError.value = '获取钓点圈详情失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

function validateForm() {
  // 重置错误
  errors.value = {
    name: '',
    images: '',
    description: ''
  }
  
  let isValid = true
  
  if (!polygonData.value.name.trim()) {
    errors.value.name = '请输入钓点圈名称'
    isValid = false
  }
  
  if (polygonData.value.images.length === 0) {
    errors.value.images = '请至少上传一张图片'
    isValid = false
  }
  
  if (!polygonData.value.description.trim()) {
    errors.value.description = '请输入钓点圈描述'
    isValid = false
  }
  
  return isValid
}

async function save() {
  if (!validateForm()) {
    return
  }
  
  // 使用组件数据而不是props
  polygonData.value.points = polygonData.value.points || []
  polygonData.value.area = calculatePolygonArea(polygonData.value.points)
  polygonData.value.centerPoint = calculatePolygonCenter(polygonData.value.points)
  
  // 只保留已上传成功的图片 URL（去掉本地 blob 预览）
    polygonData.value.images = (polygonData.value.images || []).filter(url => !url.startsWith('blob:'))
  
  try {
    const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}')
    const jwtToken = currentUser.token
    
    if (!jwtToken) {
      alert('请先登录')
      router.push('/login')
      return
    }

    const routeId = route.params.id as string
    const isUpdate = isEditMode.value

    let result;
    if (isUpdate && routeId) {
      // 编辑模式 - 使用新的更新API，只更新可编辑字段
      result = await invoke('update_fishing_circle', {
        id: routeId,
        title: polygonData.value.name || '未命名钓点圈',
        description: polygonData.value.description || '',
        pics: polygonData.value.images || []
      });
      console.log('钓点圈更新成功:', result);
    } else {
      // 创建模式 - 新建钓点圈，需要所有字段
      const points = polygonData.value.points?.map(p => ({
        latitude: p.lat,
        longitude: p.lng
      })) || [];

      result = await invoke('save_fishing_circle', {
        title: polygonData.value.name || '未命名钓点圈',
        latitude: polygonData.value.centerPoint?.lat || 0,
        longitude: polygonData.value.centerPoint?.lng || 0,
        points: points,
        pics: polygonData.value.images || [],
        area: polygonData.value.area || 0,
        description: polygonData.value.description || undefined
      });
      console.log('钓点圈创建成功:', result);
    }

    // 显示成功提示
    const event = new CustomEvent('show-notification', {
      detail: { 
        message: isUpdate ? '钓点圈已成功更新！' : '钓点圈已成功保存到服务器！', 
        type: 'success' 
      }
    });
    window.dispatchEvent(event);
    
    // 返回详情页
    if (isUpdate && routeId) {
      router.push('/circle-detail/' + routeId)
    } else {
      close();
    }
    
  } catch (error: any) {
    console.error('保存钓点圈失败:', error);
    
    // 显示错误提示
    const event = new CustomEvent('show-notification', {
      detail: { 
        message: `保存失败: ${error.message || '未知错误'}`, 
        type: 'error' 
      }
    });
    window.dispatchEvent(event);
  }
}
</script>

<style scoped>
.fishing-circle-editor {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-overlay);
  backdrop-filter: blur(4px);
  z-index: 1000;
}

.save-btn {
  background: var(--accent-primary);
  color: var(--text-inverse);
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-top: 8px;
}

.save-btn:hover {
  background: var(--accent-primary-hover);
  transform: translateY(-1px);
}

.save-btn:active {
  transform: translateY(0);
}

.save-btn:disabled {
  background: var(--bg-disabled);
  cursor: not-allowed;
  transform: none;
}

.editor-content {
  background: var(--bg-card);
  border-radius: 12px;
  width: 600px;
  max-width: 90vw;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-modal);
  overflow: hidden;
  border: 1px solid var(--border);
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border);
  flex-shrink: 0;
  background: var(--accent-primary);
}

.editor-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--text-inverse);
  font-weight: 600;
  letter-spacing: 0.5px;
}

.close-btn {
  background: var(--bg-tertiary);
  border: 1px solid var(--border);
  font-size: 18px;
  cursor: pointer;
  color: var(--text-inverse);
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: var(--bg-card);
  border-color: var(--border-hover);
}

.editor-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--text-primary);
  font-size: 14px;
  letter-spacing: 0.5px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 14px;
  box-sizing: border-box;
  background: var(--bg-input);
  color: var(--text-primary);
  transition: all 0.2s ease;
}

.form-input:focus {
  outline: none;
  border-color: var(--accent-primary);
  box-shadow: var(--shadow-focus);
}

.images-upload {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.file-input {
  display: none;
}

.upload-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid var(--border);
  background: var(--bg-input);
}

.image-item .uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  background: var(--accent-danger-bg);
  color: var(--text-inverse);
  border: none;
  border-radius: 4px;
  width: 20px;
  height: 20px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.remove-image-btn:hover {
  background: var(--accent-danger);
}

.upload-area {
  border: 1px dashed var(--border);
  border-radius: 6px;
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  background: var(--bg-input);
}

.upload-area:hover {
  border-color: var(--accent-primary);
  background: var(--bg-tertiary);
}

.add-image {
  background: var(--bg-input);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  color: var(--text-secondary);
  font-size: 11px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.points-list {
  max-height: 180px;
  overflow-y: auto;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--bg-input);
}

.points-list::-webkit-scrollbar {
  width: 6px;
}

.points-list::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
}

.points-list::-webkit-scrollbar-thumb {
  background: var(--border);
  border-radius: 3px;
}

.point-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid var(--border);
  transition: background-color 0.2s ease;
}

.point-item:hover {
  background: var(--bg-tertiary);
}

.point-item:last-child {
  border-bottom: none;
}

.point-number {
  background: var(--accent-primary);
  color: var(--text-inverse);
  border-radius: 4px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  margin-right: 10px;
  font-weight: 600;
}

.point-coords {
  flex: 1;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: var(--text-primary);
}

.remove-btn {
  background: var(--accent-danger);
  color: var(--text-inverse);
  border: none;
  border-radius: 4px;
  width: 18px;
  height: 18px;
  cursor: pointer;
  font-size: 11px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
}

.remove-btn:hover {
  background: var(--accent-danger-hover);
}

.area-display {
  background: var(--bg-input);
  padding: 12px 16px;
  border-radius: 6px;
  font-weight: 500;
  color: var(--text-primary);
  border: 1px solid var(--border);
  font-size: 14px;
}

.center-display {
  padding: 12px 16px;
  background: var(--bg-input);
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  color: var(--text-primary);
  border: 1px solid var(--border);
  font-weight: 500;
}

.description-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border);
  border-radius: 6px;
  font-family: inherit;
  font-size: 14px;
  resize: vertical;
  min-height: 60px;
  background: var(--bg-input);
  color: var(--text-primary);
}

.description-input:focus {
  outline: none;
  border-color: var(--accent-primary);
}

.points-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: 0;
  margin: 0;
}

.points-header label {
  margin: 0;
  cursor: pointer;
}

.toggle-icon {
  font-size: 12px;
  color: var(--text-secondary);
  transition: transform 0.2s;
}

.required {
  color: var(--accent-danger);
  font-weight: bold;
}

.error-message {
  color: var(--accent-danger);
  font-size: 12px;
  margin-top: 4px;
  display: block;
}

.editor-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid var(--border);
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-secondary {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.btn-secondary:hover {
  background: var(--bg-card);
}

.btn-primary {
  background: var(--accent-primary);
  color: var(--text-inverse);
}

.btn-primary:hover {
  background: var(--accent-primary-hover);
}
/* 加载和错误状态样式 */
.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: var(--text-secondary);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid var(--border);
  border-top: 4px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.error-container p {
  color: var(--text-secondary);
  margin-bottom: 8px;
}
</style>